package com.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TylerApplicationContext {

    private Map<String, BeanDefinitation> beanDefinitationMap = new HashMap<>();
    private Map<String, Object> singleObjects = new HashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();
    private Class configClass;

    public TylerApplicationContext(Class configClass) {
        this.configClass = configClass;

        // 扫描
        extracted(configClass);

        for (Map.Entry<String, BeanDefinitation> entry : beanDefinitationMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinitation beanDefinitation = entry.getValue();
            if (beanDefinitation.getScope().equals("singleton")) {
                Object bean = createBean(beanName, beanDefinitation);
                singleObjects.put(beanName, bean);
            }
        }
    }

    private Object createBean(String beanName, BeanDefinitation beanDefinitation) {
        Class clazz = beanDefinitation.getType();
        Object newInstance = null;
        try {
            newInstance = clazz.getConstructor().newInstance();

            // 依赖注入
            for (Field field : newInstance.getClass().getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    field.set(newInstance, getBean(field.getName()));
                }
            }

            // 回调
            if (newInstance instanceof BeanNameAware) {
                ((BeanNameAware)newInstance).setBeanName(beanName);
            }

            // 初始化前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                newInstance = beanPostProcessor.postProcessBeforeInitialization(newInstance, beanName);
            }

            // 初始化
            if (newInstance instanceof InitializingBean) {
                ((InitializingBean)newInstance).afterPropertiesSet();
            }

            // 初始化后
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                newInstance = beanPostProcessor.postProcessAfterInitialization(newInstance, beanName);
            }

        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        return newInstance;
    }


    public Object getBean(String beanName){
        if (!beanDefinitationMap.containsKey(beanName)) {
            throw new NullPointerException();
        }
        BeanDefinitation beanDefinitation = beanDefinitationMap.get(beanName);
        if (beanDefinitation.getScope().equals("singleton")) {
            // 单例
            Object singletonBean = singleObjects.get(beanName);
            if (singletonBean == null) {
                singletonBean = createBean(beanName, beanDefinitation);
                singleObjects.put(beanName, singletonBean);
            }
            return singletonBean;
        } else {
            // 原型
            Object prototypeBean =  createBean(beanName, beanDefinitation);
            return prototypeBean;
        }
    }

    private void extracted(Class configClass) {
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();
            path = path.replace(".", "/");

            ClassLoader classLoader = TylerApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());
            if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    String filePath = f.getPath();
                    filePath = filePath.substring(filePath.indexOf("com"), filePath.indexOf(".class"));
                    filePath = filePath.replace("\\", ".");

                    try {
                        Class clazz = classLoader.loadClass(filePath);
                        if (clazz.isAnnotationPresent(Component.class)) {
                            BeanDefinitation beanDefinitation = new BeanDefinitation();
                            beanDefinitation.setType(clazz);

                            // 缓存 beanPostProcessor
                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                BeanPostProcessor beanPostProcessor = (BeanPostProcessor) clazz.getConstructor().newInstance();
                                beanPostProcessorList.add(beanPostProcessor);
                            } else {
                                Component componentAnnotation = (Component) clazz.getAnnotation(Component.class);
                                String beanName = componentAnnotation.value();

                                if ("".equals(beanName)) {
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }

                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = (Scope) clazz.getAnnotation(Scope.class);
                                    beanDefinitation.setScope(scopeAnnotation.value());
                                } else {
                                    beanDefinitation.setScope("singleton");
                                }
                                beanDefinitationMap.put(beanName, beanDefinitation);
                            }
                        }
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
